package br.ufc.cloud;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public class Upload extends HttpServlet {
    private BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();

    public void doPost(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {

    	String name = req.getParameter("name").toLowerCase();
    	String address = req.getParameter("address");
    	String phone = req.getParameter("phone");
    	String email = req.getParameter("email");
    	
    	Map<String, BlobKey> blobs = blobstoreService.getUploadedBlobs(req);
        BlobKey blobKey = blobs.get("myFile");
    	
    	User user = new User();
    	user.setName(name);
    	user.setAddress(address);
    	user.setEmail(email);
    	user.setPhone(phone);
    	user.setPhotoBlobKey(blobKey);
    	

        addToBd(user);
        
        if (blobKey == null) {
            res.sendRedirect("/");
        } else {
            res.sendRedirect("/serve?name=" + name + "&address=" + address + "&phone=" + phone + "&email=" + email + "&blob-key=" + blobKey.getKeyString());
        }
    }
    
	public void addToBd(User user)
	{
		
		String seedHash = user.getName() + user.getEmail() + user.getAddress() + user.getPhone() + user.getPhotoBlobKey().toString();
		long id = seedHash.hashCode();
	    Key customerKey = KeyFactory.createKey("User", id + "");
	    Entity customer = new Entity("User", customerKey);
	    customer.setProperty("name", user.getName());
	    customer.setProperty("address", user.getAddress());
	    customer.setProperty("email", user.getEmail());
	    customer.setProperty("phone", user.getPhone());
	    customer.setProperty("photoBlobKey", user.getPhotoBlobKey());
	    customer.setProperty("id", id);
	    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
	    datastore.put(customer); //save it
	}
}